package com.defysoft.waukids.home;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseFragment;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.Data_Type.WK_BACKBUS_STUDENT;
import com.defysoft.waukids.Data_Type.WK_GOBUS_STUDENT;
import com.defysoft.waukids.Data_Type.WK_STATE;
import com.defysoft.waukids.Data_Type.WK_TEACHER_STATE;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.diary.DiaryDetailActivity;
import com.defysoft.waukids.main.Main_MainFrame;
import com.defysoft.waukids.message.Message_Detail_Activity;
import com.defysoft.waukids.notice.NoticeDetailActivity;
import com.defysoft.waukids.notice.Notice_Main_F;

public class Home_Main_F extends BaseFragment {
	View view;
	ListView lv;
	boolean check_single =false;
	boolean bus_refresh=false;
	final int SUCCESS = 10;
	final int MORE_SUCCESS = 9;
	final int FAIL = 8;
	final int NETWORK_ERR = 7;
	final int BUS_SUCCESS = 6;
	GridView up_gv,down_gv;
	TextView tv;

	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_Student student;
	ArrayList<WK_STATE> state;
	ArrayList<WK_TEACHER_STATE> tea_state;
	ArrayList<WK_BACKBUS_STUDENT> back_state;
	ArrayList<WK_GOBUS_STUDENT>go_state;
	WK_BACKBUS_STUDENT back_location,blank_back;
	WK_GOBUS_STUDENT go_location,blank_go;
	Home_ListAdapter list_adapter;
	boolean ListViewLock;
	String count = "",bus_rank="",check_bus ="";
	LinearLayout ly,ly_status;
	Bus_StationUp_Adapter up_adapter;
	Bus_StationDown_Adapter down_adapter;
	int up_size,down_size;
	ImageView iv_refresh;
	TextView tv_status;
	String count_bus;
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.home_main_fragment, null);
		setStartData();
		return view;
	}

	@Override
	public void setStartData() {
		super.setStartData();
		psf = new PublicSharedpreferences(getActivity());
		psf.setMembersp();
		psf.setStudentsp();
		member = psf.getMembersp();
		student = psf.getStudentsp();
		
		lv = (ListView) view.findViewById(R.id.HOME_MAIN_LISTVIEW);
		ly = (LinearLayout) view.findViewById(R.id.HOME_BUS_CONTAINER);
		tv = (TextView) view.findViewById(R.id.HOME_BUS_STATION);
		up_gv = (GridView)view.findViewById(R.id.HOME_BUS_GRID_ONE);
		down_gv = (GridView)view.findViewById(R.id.HOME_BUS_GRID_TWO);
		iv_refresh = (ImageView)view.findViewById(R.id.HOME_BUS_STATE_REFRESH);
		tv_status = (TextView) view.findViewById(R.id.HOME_MAIN_BUS_STATUS);
		ly_status = (LinearLayout) view.findViewById(R.id.HOME_MAIN_BUS_STATUS_LL);
		up_adapter = new Bus_StationUp_Adapter();
		down_adapter = new Bus_StationDown_Adapter();
		go_state = new ArrayList<WK_GOBUS_STUDENT>();
		back_state = new ArrayList<WK_BACKBUS_STUDENT>();
		
		lv.setDivider(null);
		up_gv.setAdapter(up_adapter);
		down_gv.setAdapter(down_adapter);
		
	if(member.Rank.equals("3")){
		
			ly.setVisibility(View.VISIBLE);
			iv_refresh.setVisibility(View.VISIBLE);
			ly_status.setVisibility(View.VISIBLE);
			iv_refresh.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					startNetwork(2);			
				}
			});	
			
		}else{
			ly.setVisibility(View.GONE);
			iv_refresh.setVisibility(View.GONE);
			ly_status.setVisibility(View.GONE);
		}	
	
		startNetwork(0);
		
	}
		
	void mainThread() {
		String code = "";
		if (!member.Rank.equals("3")) {
			code = "code=" + HOME_STATE_LOAD + "&FK_Cla_Tea_Code="
					+ member.Class + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School;
		} else {
			code = "code=" + HOME_STATE_LOAD + "&FK_Stu_Gob_Sta_Code="
					+ student.Code + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School;
		}
		
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					code));
			
			if (jsonObject.getBoolean("success")) {

				if (member.Rank.equals("3")) {
					state = JsonParser.state_list(jsonObject
							.getString("payload"));
				} else {
					tea_state = JsonParser.teacher_state_list(jsonObject
							.getString("payload"));
				}
				count = jsonObject.getString("count");
				onNetworkCallback(SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" where main_Thread()");
		}
		;
	}

	void moreThread() {

		String code = "";
		if (!member.Rank.equals("3")) {
			code = "code=" + HOME_STATE_MORE + "&FK_Cla_Tea_Code="
					+ member.Class + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School + "&limit="
					+tea_state.size(); 
		} else {
			code = "code=" + HOME_STATE_MORE + "&FK_Stu_Gob_Sta_Code="
					+ student.Code + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School + "&limit="
					+ state.size();
		}

		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					code));
			if (jsonObject.getBoolean("success")) {

				if (member.Rank.equals("3")) {
					state.addAll(JsonParser.state_list(jsonObject
							.getString("payload")));
				} else {
					tea_state.addAll(JsonParser.teacher_state_list(jsonObject
							.getString("payload")));
				}

				count = jsonObject.getString("count");
				onNetworkCallback(MORE_SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" moreThread()");
		}
		;

	}

	void busloadThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+HOME_BUS_STATE_LOAD
					+"&FK_Sch_Bac_Stu_Code="+member.School
					+"&FK_Stu_Bac_Stu_Code="+student.Code
					));
			if (jsonObject.getBoolean("success")) {
				bus_rank = jsonObject.getString("rank");
				check_bus = jsonObject.getString("payload");
				count_bus = jsonObject.getString("count");
				
			if(check_bus.equals("0")){
				if(bus_rank.equals("1")|| bus_rank.equals("0")){						
					go_state=JsonParser.gobus_student(jsonObject.getString("station"));
					go_location =JsonParser.gobus_state(check_bus);
				}else if(bus_rank.equals("2")|| bus_rank.equals("4")){
					back_state=JsonParser.backbus_student(jsonObject.getString("station"));
					back_location=JsonParser.backbus_state(check_bus);		
				}
			}else{
				if(bus_rank.equals("1") || bus_rank.equals("0")){			
				 	go_state=JsonParser.gobus_student(jsonObject.getString("station"));
					go_location =JsonParser.gobus_state(check_bus);
			 }else if(bus_rank.equals("2")|| bus_rank.equals("4")){				
					back_state=JsonParser.backbus_student(jsonObject.getString("station"));
					back_location=JsonParser.backbus_state(check_bus);			
					
					}
			}	
			
			
			onNetworkCallback(BUS_SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+"  busloadThread()");
		}
		
		;
	}
	

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 0:
					mainThread();
					break;
				case 1:
					moreThread();
					break;
				case 2:
					busloadThread();
					break;
				}
			}
		});
		firstThread.start();
		if(bus_refresh==false){
			startDIal();
			bus_refresh=true;
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);

		switch (_message.what) {

		case SUCCESS:
		
			
			list_adapter = new Home_ListAdapter();
			lv.setAdapter(list_adapter);
			lv.setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub

					int lastItem = totalItemCount - visibleItemCount;
					if (firstVisibleItem >= lastItem && totalItemCount != 0
							&& ListViewLock == false) {
						if (member.Rank.equals("3")) {
							if (state.size() < Integer.parseInt(count)) {
								ListViewLock = true;
								startNetwork(1);
							}
						} else {
							if (tea_state.size() < Integer.parseInt(count)) {
								ListViewLock = true;
								startNetwork(1);
							}
						}
					}

				}
			});
			startThread(2);
			
			break;

		case MORE_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			list_adapter.notifyDataSetChanged();
			break;
		case BUS_SUCCESS:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			
			
			
			if(member.Rank.equals("3")){
				bus_refresh=false;
				ly.setVisibility(View.VISIBLE);
				ly_status.setVisibility(View.VISIBLE);
				iv_refresh.setVisibility(View.VISIBLE);
				if(count_bus.equals("0")){
					ly.setVisibility(View.GONE);
					ly_status.setVisibility(View.GONE);
					iv_refresh.setVisibility(View.GONE);
				}
			}else{
				
				ly.setVisibility(View.GONE);
				ly_status.setVisibility(View.GONE);
			}
			
			
			if (bus_rank.equals("1")||bus_rank.equals("0")){
				tv.setVisibility(View.VISIBLE);
				tv_status.setText("등원 버스 노선");
				if(check_bus.equals("0") && bus_rank.equals("1")){
					tv.setText("등원 버스가 출발 하였습니다.");
				}else if(bus_rank.equals("0")){
					tv.setText("등원 버스 운행이 종료 되었습니다.");
				}else{
					tv.setText("현재위치 : "+go_location.Gob_Stu_Address);
				}
				
				if(go_state.size()%2==0){
					check_single = false;
					up_size=go_state.size()/2;
					up_gv.setNumColumns(up_size);	
					up_adapter.notifyDataSetChanged();
					down_size=go_state.size()/2;		
					down_gv.setNumColumns(down_size);
					down_adapter.notifyDataSetChanged();
					
				}else{
					
					up_size=(go_state.size()/2)+1;
					up_gv.setNumColumns(up_size);
					up_adapter.notifyDataSetChanged();
					down_size=(go_state.size()/2)+1;
					blank_go = new WK_GOBUS_STUDENT();
					go_state.add(blank_go);
					check_single = true;
					down_gv.setNumColumns(down_size);
					down_adapter.notifyDataSetChanged();
					}
				
				
			}else if(bus_rank.equals("2") || bus_rank.equals("4")){
				tv.setVisibility(View.VISIBLE);
				tv_status.setText("하원 버스 노선");
				
			if(check_bus.equals("0") && bus_rank.equals("2")){
				
					tv.setText("하원 버스가 출발 하였습니다.");
				
				}else if(bus_rank.equals("4")){
					
						tv.setText("하원버스 운행이 종료 되었습니다.");
						
				}else{
					tv.setText("현재위치 : "+back_location.Bac_Stu_Address);
				}
				
			if(back_state.size()%2==0){
				check_single = false;
				up_size=back_state.size()/2;
				up_gv.setNumColumns(up_size);
				up_adapter.notifyDataSetChanged();
				down_size=back_state.size()/2;		
				down_gv.setNumColumns(down_size);
				down_adapter.notifyDataSetChanged();
				
			}else{
				up_size=(back_state.size()/2)+1;
				up_gv.setNumColumns(up_size);
				up_adapter.notifyDataSetChanged();
				down_size=(back_state.size()/2)+1;
				blank_back = new WK_BACKBUS_STUDENT();
				go_state.add(blank_go);
				check_single = true;
				down_gv.setNumColumns(down_size);
				down_adapter.notifyDataSetChanged();
				}
				
			}

			endDIal();
			break;
		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(getActivity(), (String) _message.obj,
					Toast.LENGTH_SHORT).show();
			break;

		case NETWORK_ERR:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			((Main_MainFrame)getActivity()).sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"HOME_MAIN_F", member.Email);
			break;
		}

	}

	public class Bus_StationUp_Adapter extends ArrayAdapter<String>{

		public Bus_StationUp_Adapter() {
			super(getActivity(), android.R.layout.simple_list_item_1);
		}

		@Override
		public int getCount() {
			return up_size;
			
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Bus_Holder bus_holder;
			if(convertView==null){
				bus_holder = new Bus_Holder();
				convertView = getActivity().getLayoutInflater().inflate(R.layout.home_bus_station_grid_row,null);
				bus_holder.iv_station = (ImageView)convertView.findViewById(R.id.BUS_STATION_GRID_IV);
				bus_holder.ly[0] = (LinearLayout)convertView.findViewById(R.id.BUS_STATION_GRID_CONTAINER);
				bus_holder.ly[1] = (LinearLayout)convertView.findViewById(R.id.BUS_STATION_GRID_LL);
				
				convertView.setTag(bus_holder);
			}else{
				bus_holder = (Bus_Holder)convertView.getTag();
			}
			
			if(bus_rank.equals("1") || bus_rank.equals("0")){
				if(go_state.get(position).Gob_Stu_Order.equals(go_location.Gob_Stu_Order)){
					bus_holder.iv_station.setImageResource(R.drawable.bus_come);
				}else{
					bus_holder.iv_station.setImageResource(R.drawable.icon_on);
				}				
			}else if(bus_rank.equals("2")|| bus_rank.equals("4")) {
				if(back_state.get(position).Bac_Stu_Order.equals(back_location.Bac_Stu_Order)){
					bus_holder.iv_station.setImageResource(R.drawable.bus_come);
				}else{
					bus_holder.iv_station.setImageResource(R.drawable.icon_on);
				}
				
			}
			

			return convertView;
		}
	}
	
	public class Bus_StationDown_Adapter extends ArrayAdapter<String>{

		public Bus_StationDown_Adapter() {
			super(getActivity(), android.R.layout.simple_list_item_1);
		}

		@Override
		public int getCount() {
			
			return down_size;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Bus_Holder bus_holder;
			if(convertView==null){
				bus_holder = new Bus_Holder();
				convertView = getActivity().getLayoutInflater().inflate(R.layout.home_bus_station_grid_row,null);
				bus_holder.iv_station = (ImageView)convertView.findViewById(R.id.BUS_STATION_GRID_IV);

				bus_holder.ly[0] = (LinearLayout)convertView.findViewById(R.id.BUS_STATION_GRID_CONTAINER);
				bus_holder.ly[1] = (LinearLayout)convertView.findViewById(R.id.BUS_STATION_GRID_LL);
				convertView.setTag(bus_holder);
			}else{
				bus_holder = (Bus_Holder)convertView.getTag();
			}
				
			if(bus_rank.equals("1")|| bus_rank.equals("0")){
				if(go_state.get(go_state.size()-(position+1)).Gob_Stu_Order.equals(go_location.Gob_Stu_Order)){
					bus_holder.iv_station.setImageResource(R.drawable.bus_come);
				}else{
					bus_holder.iv_station.setImageResource(R.drawable.icon_on);
				}
				
			}else if (bus_rank.equals("2")|| bus_rank.equals("4")){
				if(back_state.get(back_state.size()-(position+1)).Bac_Stu_Order.equals(back_location.Bac_Stu_Order)){
					bus_holder.iv_station.setImageResource(R.drawable.bus_come);
				}else{
					bus_holder.iv_station.setImageResource(R.drawable.icon_on);
				}
				
			}
			
				if(check_single==true){
					if(position==0){
						bus_holder.ly[0].setVisibility(View.INVISIBLE);
					}else{
						bus_holder.ly[0].setVisibility(View.VISIBLE);
					}
				}else{
					bus_holder.ly[0].setVisibility(View.VISIBLE);
			}
		
			return convertView;
		}
	}
	
	class Bus_Holder{
		ImageView iv_station;
		LinearLayout ly[] = new LinearLayout[2];
	}
	
	public class Home_ListAdapter extends ArrayAdapter<String> {

		public Home_ListAdapter() {
			super(getActivity(), android.R.layout.simple_list_item_1);
		}

		@Override
		public int getCount() {
			if (member.Rank.equals("3")) {
				return state.size();
			} else {
				return tea_state.size();
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Home_ListHolder holder;
			final int pos = position;
			if (convertView == null) {
				holder = new Home_ListHolder();
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.home_list_row, null);
				holder.tv = (TextView) convertView
						.findViewById(R.id.HOME_LIST_ROW_TV);
			
				convertView.setTag(holder);
			} else {
				holder = (Home_ListHolder) convertView.getTag();
			}
			
			if(position%2==0){
				holder.tv.setBackgroundColor(0x44ffffff);
			}else{
				holder.tv.setBackgroundColor(0x88ffffff);
			}
			
			
			
			
			if (member.Rank.equals("3")) {
				holder.tv.setText(state.get(position).Sta_Date+ " "+state.get(position).Sta_Message);
				/*if(!state.get(position).Sta_FK_Code.equals("0")){
					holder.tv.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(state.get(pos).Sta_Rank.equals(GCM_NOTIEC_CODE)){
								((Main_MainFrame)getActivity()).sqlite_Connect.delete_New_Notice(Integer.parseInt(state.get(pos).Sta_FK_Code));
								((Main_MainFrame)getActivity()).fragment_notify(1);
								Intent i  = new Intent(getActivity(),NoticeDetailActivity.class);
								i.putExtra("PK_Not_Code", state.get(pos).Sta_FK_Code);
								startActivityForResult(i,PublicConstant.START_NOTICE_DETAIL);
							}
							if (state.get(pos).Sta_Rank.equals(GCM_DIARY_CODE)){
								((Main_MainFrame)getActivity()).sqlite_Connect.delete_New_Diary(Integer.parseInt(state.get(pos).Sta_FK_Code));
								((Main_MainFrame)getActivity()).fragment_notify(2);
								Intent i  = new Intent(getActivity(),DiaryDetailActivity.class);
								i.putExtra("PK_Dia_Code", state.get(pos).Sta_FK_Code);
								startActivityForResult(i,PublicConstant.START_DIARY_DETAIL);
							}
							
						}
					});
				}*/
			} else {		
				  holder.tv.setText(tea_state.get(position).Tea_Date+" "+tea_state.get(position).Tea_Message);		
				 
				  /* if(!tea_state.get(position).Tea_FK_Code.equals("0")){
					
						 holder.tv.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								if(tea_state.get(pos).Tea_Rank.equals(GCM_NOTIEC_CODE)){
									Intent i  = new Intent(getActivity(),NoticeDetailActivity.class);
									i.putExtra("PK_Not_Code", state.get(pos).Sta_FK_Code);
									startActivityForResult(i,PublicConstant.START_NOTICE_DETAIL);
								}
								if (tea_state.get(pos).Tea_Rank.equals(GCM_MESSAGE_CODE)){
									((Main_MainFrame)getActivity()).sqlite_Connect.delete_New_Mas(Integer.parseInt(tea_state.get(pos).Tea_FK_Code));
									Intent i  = new Intent(getActivity(),Message_Detail_Activity.class);
									i.putExtra("PK_Mes_Code", tea_state.get(pos).Tea_FK_Code);
									i.putExtra("Mes_Category", tea_state.get(pos).Tea_Mes_Category);
									startActivityForResult(i, PublicConstant.START_MESSAGE);
								}
							}
						});
					}*/
				  
			}
						
			return convertView;
		}
	}

	class Home_ListHolder {
		TextView tv;
	}
	
}
